package sealte.test.crazyjavalearning.test.IoC;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class MyXMLContext {

	private Map<String,String> beans = new HashMap<String,String>();
	private Map<String,Map<String,String>> properties = new HashMap<String,Map<String,String>>();
	
	public void initContext() throws Exception{
		String xmlPath = MyXMLContext.class.getResource("").getPath()+"beans.xml";
		SAXBuilder sb = new SAXBuilder();
		Document doc = sb.build(new FileInputStream(xmlPath));
		Element root = doc.getRootElement();
		List<Element> beanEL = root.getChildren();
		for(Element bean:beanEL){
			String id = bean.getAttributeValue("id");
			String cla = bean.getAttributeValue("class");
			beans.put(id, cla);
			List<Element> propertyEL = bean.getChildren();
			Map<String,String> propertyMap = new HashMap<String,String>();
			for(Element property:propertyEL){
				String name = property.getAttributeValue("name");
				String ref = property.getAttributeValue("ref");
				String value = property.getAttributeValue("value");
				if(null==ref && null!=value){
					propertyMap.put(name, "value:"+value);
				}else if(null==value && null!=ref){
					propertyMap.put(name, "ref:"+ref);
				}
			}
			properties.put(id, propertyMap);
		}
	}
	
	public String getBean(String id){
		return beans.get(id);
	}
	
	public Map<String,String> getProperties(String id){
		return properties.get(id);
	}
}
